#pragma once

#include <QString>
#include <QFile>
#include <QTimer>
#include <QQueue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "qtc_alarm_core/AlarmEvent.h"

namespace qtc_alarm_persist {

class ESSink : public QObject {
  Q_OBJECT
public:
  struct Config {
    QString es_uri {"http://localhost:9200"};
    QString index_prefix {"Accelerator"};
    int     bulk_size {1000};
    int     flush_interval_ms {1000};
    bool    dry_run {true};
    QString log_file {"essink_bulk.log"};
  };

  explicit ESSink(const Config& cfg, QObject* parent = nullptr);
  ~ESSink();

  void start();
  void stop();

  void append(const qtc_alarm_core::AlarmEvent& ev);
  void flush();

signals:
  void error(const QString&);
  void info(const QString&);

private slots:
  void onFlushTimer();

private:
  QString indexNameFor(const qtc_alarm_core::AlarmEvent& ev) const;
  QByteArray toBulkLine(const qtc_alarm_core::AlarmEvent& ev) const;
  void sendBulk(const QByteArray& ndjson);

  Config m_cfg;
  QQueue<qtc_alarm_core::AlarmEvent> m_queue;
  QTimer  m_timer;
  QFile   m_log;
  QNetworkAccessManager m_net;
};

} // namespace qtc_alarm_persist